package cn.itcast.erp.interceptor;

import cn.itcast.erp.annotation.CheckPower;
import cn.itcast.erp.dao.mapper.MenuMapper;
import cn.itcast.erp.entity.Emp;
import cn.itcast.erp.entity.Menu;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;


@Component
public class PowerInterceptor implements HandlerInterceptor {

    @Resource
    private MenuMapper mm;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        List<Menu> userMenu = (List<Menu>)request.getSession().getAttribute("userMenuList");
        // 当前用户拥有的权限 List
        List<String> userMenuList = new ArrayList<>();
        for (Menu menu : userMenu) {
            userMenuList.add(menu.getMenuname());
        }

        // 获取到当前的请求所对应的Handler上的注解中的value的值
        HandlerMethod hm = (HandlerMethod) handler;
        if (hm.hasMethodAnnotation(CheckPower.class)) {

            CheckPower annotation = hm.getMethodAnnotation(CheckPower.class);
            String value[] = annotation.value();

            for (String s : value) {
                if (userMenuList.contains(s)) {
                    return true;
                }
            }

            }

        return false;
    }


}
